package com.sporteamws;
import java.io.BufferedReader;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
 
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;

public class C2DMRegistrationReceiver extends BroadcastReceiver 
{
	String FacebookId;
	BufferedReader in = null;
	HttpResponse response;
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		String action = intent.getAction();
		Log.w("C2DM", "Registration Receiver called");
		
		String registrationId = null;
		if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) 
		{
			Log.w("C2DM", "Received registration ID");
			
			//get registration id from c2dm registration
			registrationId = intent.getStringExtra("registration_id");
			
			//get registration error(null if everything is OK 
			String error = intent.getStringExtra("error");

			Log.w("C2DM", "dmControl: registrationId = " + registrationId + ", error = " + error);
					
			String deviceId = Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
					
			//createNotification(context, registrationId);
			sendRegistrationIdToServer(deviceId, registrationId);
			
			// Also save it in the preference to be able to show it later
			saveRegistrationId(context, registrationId);
		}
		
	}

	private void saveRegistrationId(Context context, String registrationId) 
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putString(MainActivity.AUTH, registrationId);
		edit.commit();
	}

	public void createNotification(Context context, String registrationId) 
	{
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(com.sporteamws.R.drawable.new_msg,
				"Registration successful", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		Intent intent = new Intent(context, RegistrationResultActivity.class);
		intent.putExtra("registration_id", registrationId);
		PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
				
		notification.setLatestEventInfo(context, "Registration","Successfully registered", pendingIntent);
				
		notificationManager.notify(0, notification);
	}
	
    //set policies for android 4 and up (for use of network IO from main UI thread)
	 public void SetPolicies()
	 {
		 /* 
	        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
	        .detectDiskReads()
	        .detectDiskWrites()
	        .detectNetwork()   // or .detectAll() for all detectable problems
	        .penaltyLog()
	        .build());
	        
	         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
	        .detectLeakedSqlLiteObjects()
	        .detectLeakedSqlLiteObjects()
	        .penaltyLog()
	        .penaltyDeath()
	        .build()); */
	 }
	 
	// Incorrect usage as the receiver may be canceled at any time
	// do this in an service and in an own thread
	public void sendRegistrationIdToServer(String deviceId,String registrationId)
	{
		
		//load facebook id from secure storage
		FacebookId = SharedPref.facebookID;
		
		//set policies for android 4 and up
		SetPolicies();
		
		Log.w("facebook id sent in c2dm reg= ", FacebookId);
		
		try 
		{
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet("http://sporteamws.appspot.com/c2dmRegistration?deviceid="
					+ deviceId + "&registrationid=" + registrationId
					+ "&facebookid=" + FacebookId);
			response = client.execute(request);
		}
		catch (Exception ex)
		{
			Log.e("Http error",ex.toString());
		}
			
		
	}
}
